<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      :show-close="false"
    >
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="70px" class="demo-ruleForm">
        <!-- <el-form-item label="用户">
          <el-select
            v-model="ruleForm.user_id"
            size="mini"
            placeholder="请选择用户"
            style="width: 100%"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
         <el-form-item label="用户名" prop="name" >
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"  />
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          v-if="title=='新增'"
         
        >
          <el-input v-model="ruleForm.password" />
        </el-form-item>
         <el-form-item
          label="密码"
          prop=""
          v-if="title=='编辑'"
         
        >
          <el-input v-model="ruleForm.password" placeholder="留空不修改" />
        </el-form-item>
        <el-form-item
          label="状态"
          prop="status"
        
        >
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁止</el-radio>
          </el-radio-group>
        </el-form-item>
         <!-- <el-form-item
          label="是否为运维人员"
          prop="status"
         
        >
         <el-radio-group v-model="createForm.admin_type">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item> -->
     



        <el-form-item label="年龄" prop="age">
           <el-input-number v-model="ruleForm.age"   size="mini"  :min="18" :max="100" ></el-input-number>
          <!-- <el-input v-model="ruleForm.age" size="mini" type="number" style="width: 100%" /> -->
        </el-form-item>
        <el-form-item label="职业">
          <el-input v-model="ruleForm.post" size="mini" placeholder="请输入职业" />
        </el-form-item>
        <el-form-item label="电话" prop="telephone">
          <el-input v-model="ruleForm.telephone" size="mini" type="text" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="班组" prop="group_id">
          <el-select
            v-model="ruleForm.group_id"
            size="mini"
            placeholder="请选择班组"
            style="width: 100%"
          >
            <el-option
              v-for="item in groupList"
              :key="item.id"
              :label="item.group_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select
            v-model="ruleForm.roles"
           
            size="mini"
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item style="display: flex;justify-content: flex-end">
          <el-button type="primary" size="mini" @click="resetForm">取消</el-button>
          <el-button type="primary" size="mini" @click="addOrEdit">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { detailWorker, updateWorker, createWorker, operationRole, groupList, worker } from '@/api/operations'
import { getToken } from '@/utils/auth'
export default {
  name: 'detail',
  props: {
    dialogVisible: {
      type: Boolean,
      default: true
    },
    title: {
      type: String,
      default: '新增'
    },
    id: {
      type: Number,
      default: 0
    }
  },
  data() {
    var checkEmail = (rule, value, callback) => {
    const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
    if (!value) {
      return callback(new Error('邮箱不能为空'))
    }
    setTimeout(() => {
      if (mailReg.test(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的邮箱格式'))
      }
    }, 100)
  }
    return {
      groupList: [], // 班组人员列表
      userList: [], // 企业用户列表
      roles: [], // 运维人员角色
      timeArr: [],
      header: {},
      baseURL: process.env.VUE_APP_BASE_API,
      ruleForm: {
        name: '',
        telephone: '',
        age: '',
        post: '',
        group_id: null,
        roles: null,
        status:1,
        password:'',
        email:''

      },
      rules: {
        telephone: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          { validator: function(rule, value, callback) {
            if (/^1[345789]\d{9}$/.test(value) === false) {
              callback(new Error('请输入正确的联系方式'))
            } else {
              callback()
            }
          }, trigger: 'blur' }

        ],
        
        name:[
          { required: true, message: '请输入用户', trigger: 'blur' }

        ],
        
        password:[
          { required: true, message: '请输入密码', trigger: 'blur' },
               { min: 6, max: 60, message: '长度在 6 到 60 个字符', trigger: 'blur' }

        ],
        email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail,trigger: 'blur'}

        ],
        group_id: [
          { required: true, message: '请选择班组', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.header['Authorization'] = 'Bearer ' + getToken()
    this.header['Lang'] = 'zh-CN'
    // 获取运维人员角色
    this.getRole()
    // 获取班组列表
    this.getGroupList()
    // 获取企业用户列表
    this.getUserList()
    // worker().then(res => {
    //   this.userList = res.data.data
    // })
  },
  mounted() {
    // 编辑
    if (this.id) {
      this.getDetailById(this.id)
    }
  },
  methods: {
     OnSubscribe() {
      //邮箱验证的正则表达式
      const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
      let str = this.ruleForm.email;
      if (reg.test(str)) {
        // 这里是邮箱验证成功的代码
      return
      } else {
            this.$message.warning("邮箱格式错误");
      }
    },
    // 获取企业用户列表
    getUserList() {
      // console.log('企业用户列表')
    },
    // 获取班组列表
    getGroupList() {
      groupList({ offset: 0, limit: 1, pageType: 'all' }).then(res => {
        this.groupList = res.data.groups
      })
    },
    // 运维人员角色
    getRole() {
      operationRole().then(res => {
        this.roles = []
        for (const key in res.data) {
          const obj = {}
          obj.id = key
          obj.name = res.data[key]
          this.roles.push(obj)
        }
       
      })
    },
    // 获取详情
    getDetailById(id) {
      detailWorker({ id }).then(res => {
        this.ruleForm = res.data
        this.ruleForm.roles = this.ruleForm.roleIds[0].toString()
      })
    },
    // 新增、编辑
    addOrEdit() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (this.id) {
            //  是编辑
            updateWorker(this.ruleForm).then(res => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.$emit('confirm')
            })
          } else {
            //  是新增
            createWorker(this.ruleForm).then(res => {
              this.$message({
                message: '新增成功',
                type: 'success'
              })
              this.$emit('confirm')
            })
          }
        }
      })
    },
    handleAvatarSuccess(res, file) {
      console.log(res, file)
      this.ruleForm.company_logo = res.data.realPath
    },
    handleAvatarSuccess1(res, file) {
      this.ruleForm.company_cert = res.data.realPath
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 时间选择
    timeConfirm(e) {
      this.ruleForm.company_start = e[0]
      this.ruleForm.company_end = e[1]
    },
    // 表单重置
    resetForm() {
      this.$refs['ruleForm'].resetFields()
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border-radius: 10px;
    border: 1px dashed #cccccc;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    border-radius: 10px;
  }
</style>
